package com.coldlz.mmp.proxy;


import cn.hutool.core.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public class RemoteClientFactory {
    private static final Logger log = LoggerFactory.getLogger(RemoteClientFactory.class);
    private static final ConcurrentHashMap<String, RemoteClient> remoteClientMap = new ConcurrentHashMap<>();

    public static void removeAndDestroy(RemoteClient remoteClient) {
        String clientId = remoteClient.getClientId();
        remoteClientMap.remove(clientId);
        remoteClient.destroy();
    }

    // 根据ip端口生成客户端
    public static synchronized RemoteClient getClient(UserContext userContext) {
        String clientId = getClientId(userContext);
        return remoteClientMap.get(clientId);
    }


    public static RemoteClient create(UserContext userContext) {
        String clientId = getClientId(userContext);
        return remoteClientMap.computeIfAbsent(clientId, clientIdKey -> new RemoteClient(userContext, clientIdKey));
    }

    private static String getClientId(UserContext userContext) {
        ProxyInfo info = userContext.getProxyInfo();
        Assert.isTrue(info.getHost() != null, () -> new ProxyException("host不能是空"));
        Assert.isTrue(info.getPort() > 0 && info.getPort() < 65505, () -> new ProxyException("port参数错误" + info.getPort()));
        return info.getHost() + ":" + info.getPort() + "(" + userContext.getSessionId() + ")";
    }

}
